<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<template>
  <link rel="stylesheet" href="../rules/colors.css">
  <link rel="stylesheet" href="../rules/sizing.css">
  <link rel="stylesheet" href="../rules/translation.css">
  <style>
    :host {
      display: block;
    }
    span {
      font-size: 10px;
    }
  </style>
  <div id="target">
    <span>I am in a custom element's shadowroot, registered in an import with linked stylesheets!</span>
  </div>
</template>
<script>
  (function() {
    var ownerDocument = document._currentScript.ownerDocument;
    var t = ownerDocument.querySelector('template');
    var proto = Object.create(HTMLElement.prototype);
    proto.createdCallback = function() {
      var sr = this.createShadowRoot();
      var links = t.content.querySelectorAll('link[rel="stylesheet"]');
      for (var i = 0, l; i < links.length; i++) {
        l = links[i];
        var url = new URL(l.getAttribute('href'), ownerDocument.baseURI);
        var s = document.createElement('style');
        s.textContent = '@import "' + url.href + '";';
        t.content.replaceChild(s, l);
      }
      var styles = t.content.querySelectorAll('style').array();
      Polymer.styleResolver.loadStyles(styles, t.ownerDocument.baseURI, function() {
        sr.appendChild(t.content.cloneNode(true));
        this.dispatchEvent(new CustomEvent('custom-style-loaded', {bubbles: true}));
      });
    };
    document.registerElement('custom-style', {prototype: proto});
  })();
</script>
